Fund = {
	create:function(){
		if(Valid.validate($('#filter_create_fund_form'),true)){
			Ajax.run("fundService.saveFund",
				function(data){
					if(data == -1){ // not logged in
						Fund.data = Fundr.getAjaxData($('div#pp_full_res'));
						Fund.awaitingLogin = true;
						if(Cookie.get('lastLoggedIn') != ""){ // has logged in before
							Modal.open('loginForm');
						} else {
							Modal.open('signupForm');
						}
					} else if(data.length == 32){
						Modal.close();
						Fund.query();
					} else{
						alert('error creating fund');
					}
				},
				Fundr.getAjaxData($('div#pp_full_res'))
			);
		}
	},
	data:{},
	awaitingLogin:false,
	query:function(){
		Ajax.run("fundView.renderFunds",
			function(data){
				Fund.expandedFund = "";
				Fund.isExpanding = false;
				$('#layout-funds').fadeOut(function(){
					$('#layout-funds').html(data);
					$('#layout-funds').slideDown();
				});
			},
			Fundr.getAjaxData($('#filterSet_Search'))
		);
	},
	activateFavorites:function(){
		$(document).on('mouseover','img.not_favorite_this',function(){
			var $this = $(this);
			var id = $this.attr('id').split('_')[1];
			var $that = $('#fav_'+id);
			$that.removeClass('hidden');
			$this.addClass('hidden');
		});
		
		$(document).on('mouseout','img.favorite_this',function(){
			var $this = $(this);
			var id = $this.attr('id').split('_')[1];
			var $that = $('#notfav_'+id);
			$that.removeClass('hidden');
			$this.addClass('hidden');
		});
	},
	addFavorite:function(fundID){
		var $favSpan = $('#favorite_'+fundID);
		var $notfavSpan = $('#notfavorite_'+fundID);
		$notfavSpan.hide();
		$favSpan.show();
		Ajax.run("userService.addFavorite",
			function(data){},
			{fundID:fundID}
		);
	},
	removeFavorite:function(fundID){
		var $favSpan = $('#favorite_'+fundID);
		var $notfavSpan = $('#notfavorite_'+fundID);
		$notfavSpan.show();
		$favSpan.hide();
		Ajax.run("userService.removeFavorite",
			function(data){},
			{fundID:fundID}
		);
	},
	timers:{},
	throttle:function(fn,key,delay,args){
		var delay = delay || 2500;
		// clear out all the timers started for this key
		for(key in Fund.timers){
			clearTimeout(Fund.timers[key]);
		}
		
		var context = this, args = args;
		Fund.timers[key] = setTimeout(function () {
			delete Fund.timers[key];
			fn.apply(context, args);
		}, delay);
	},
	support:function(fundID){
		Fund.expand2(fundID,'support',210);
		Fund.loadPaymentArea2(fundID);
	},
	expandedFund:"",
	isExpanding:false,
	expand:function(fundID){
		if(fundID != Fund.expandedFund){
			if(Fund.expandedFund != ""){
				Fund.collapse(Fund.expandedFund);
			}
			Fund.isExpanding = true;
			Fund.expandedFund = fundID;
			var $fund = $('#fund_'+fundID);
			var $fundPhoto = $fund.find('td.fund-contents-photo');
			var $fundTable = $fund.find('table.fund-contents'); 
			var $fundDescription = $fund.find('.fund-main-top-description');
			var $fundProgress = $fund.find('.fund-progress-bar');
			var $collapseButton = $fund.find('.collapse');
			var $expandButton = $fund.find('button.support');
			var $confirmButton = $fund.find('button.confirm');
			var $meta = $fund.find('.fund-contents-meta');
			
			$expandButton.fadeOut(300);
			$fundProgress.animate({height:'238px'},300);
			$fundTable.animate({height:'212px'},300);
			$fundPhoto.fadeOut(300);
			$meta.fadeOut(300);
			$collapseButton.fadeIn(300);
			$fundDescription.fadeOut(300,function(){
				Fund.isExpanding = false;
				Fund.loadPaymentArea(fundID);
			});
		}
	},
	collapse:function(fundID){
		var $fund = $('#fund_'+fundID);
		var $fundPhoto = $fund.find('td.fund-contents-photo');
		var $fundTable = $fund.find('table.fund-contents'); 
		var $fundDescription = $fund.find('.fund-main-top-description');
		var $fundProgress = $fund.find('.fund-progress-bar');
		var $collapseButton = $fund.find('.collapse');
		var $paymentArea = $fund.find('.fund-paymentArea');
		var $expandButton = $fund.find('button.support');
		var $meta = $fund.find('.fund-contents-meta');
		
		$fundProgress.animate({height:'136px'},300);
		$fundTable.animate({height:'111px'},300);
		$fundPhoto.fadeIn('fast');
		$collapseButton.fadeOut(300);
		$fundDescription.fadeIn('fast');
		$paymentArea.html('&nbsp;');
		$paymentArea.hide();
		Fund.expandedFund = "";
		$expandButton.fadeIn(300);
		$meta.fadeIn(300);
		for(key in Fund.loadingPaymentArea){
			try{
				Fund.loadingPaymentArea[key].abort();
			} catch(e){
				/*do nothing*/
			}
		}
	},
	adjustProgressHeights:function(){
		$('.fund').each(function(){
			Fund.adjustProgressHeight($(this));
		});
	},
	loadingPaymentArea:{},
	adjustProgressHeight:function($fund){
		var $this = $fund;
		var $progress = $this.find('.fund-progress-bar');
		$progress.height($this.height());
	},
	loadPaymentArea:function(fundID){
		var $paymentArea = $('#fund_'+fundID).find('.fund-paymentArea');
		var $loadingIcon = $('#fund_'+fundID).find('.fund-contents-loading');
		$loadingIcon.fadeIn(300);

		Fund.loadingPaymentArea[fundID] = Ajax.run("paymentView.renderPaymentArea",
			function(data){
				$paymentArea.hide();
				$loadingIcon.hide();
				$paymentArea.html(data);
				$paymentArea.fadeIn(300);
				Fund.changeLimit(fundID);
				Fund.assessPaymentDate(fundID);
			},
			{fundID:fundID}
		);
	},
	changeLimit:function(fundID){
		var $fund = $('#fund_'+fundID);
		$('div[class*=limit_]').hide();
		var limit = Radio.get('limit_'+fundID);
		$fund.find('.limit_'+limit).show();
	},
	changeSinglePayment:function(fundID){
		var paymentPlan = Radio.get('type');
		var $fund = $('#fund_'+fundID);
		var $frequencyTD = $fund.find('.frequency_td');
		var $limitTD = $fund.find('.limit_td');
		var $payment_method_number = $fund.find('.payment_method_number');
		var $define_number = $fund.find('.define_number');
		var $define_word = $fund.find('.define_word');
		var $installments = $fund.find('div.limit_1');
		var $date = $fund.find('div.date_div');
		var $paymentMethodTD = $fund.find('.payment_method_td');
		
		if(paymentPlan == 1){
			Fund.loadPlan(fundID);
			$define_number.text('3');
			$define_word.text('Installments');
			$payment_method_number.text('4');
			$installments.fadeIn(300);
			$date.fadeIn(300);
			$installments.parent().css('width','20%');
			$paymentMethodTD.css('width','110px');
			$frequencyTD.fadeIn(100);
			$limitTD.fadeIn(100);
		} else {
			Fund.savePlan(fundID);
			Fund.loadPlan(fundID,true);
			$frequencyTD.hide();
			$limitTD.hide();
			$define_number.text('1');
			$define_word.text('Payment');
			$payment_method_number.text('2');
			$installments.hide();
			$date.hide();
		}
	},
	paymentPlan:{},
	singlePlan:{
		limit:1,
		installments:1
	},
	savePlan:function(fundID){ // saves interface plan
		var $fund = $('#fund_'+fundID);
		Fund.paymentPlan.limit = Radio.get('limit_'+fundID);
		Fund.paymentPlan.installments = $fund.find('input[name=installments]').val() || "";
		Fund.paymentPlan.date = $fund.find('input[name=date]').val() || "";
	},
	loadPlan:function(fundID,loadSinglePlan){
		var loadSinglePlan = loadSinglePlan || false;
		var $fund = $('#fund_'+fundID);
		var plan = Fund.paymentPlan;
		if(loadSinglePlan){
			plan = Fund.singlePlan;
			plan.date = $('[name=today]:first').val();
		}
		Radio.set('limit_'+fundID,plan.limit);
		$fund.find('input[name=installments]').val(plan.installments);
		$fund.find('input[name=date]').val(plan.date);
	},
	assessPaymentDate:function(fundID){
		var $fund = $('#fund_'+fundID);
		var date = $fund.find('input[name=date]').val();
		var today = $fund.find('input[name=today]').val();
		var $text = $fund.find('.first_payment_today');
		if(date == today) {
			$text.text('Today');
			$text.css('fontWeight','bold');
		} else {
			$text.text('On');
			$text.css('fontWeight','normal');
		}
	},
	showNotLoggedInPayments:function(fundID){
		var $fund = $('#fund_'+fundID);
		var $notLoggedDiv = $fund.find('.not_logged_in_payments');
		var $logInDiv = $fund.find('.login_for_payments');
		$logInDiv.hide();
		$notLoggedDiv.fadeIn(300);
	},
	hideNotLoggedInPayments:function(fundID){
		var $fund = $('#fund_'+fundID);
		var $notLoggedDiv = $fund.find('.not_logged_in_payments');
		var $logInDiv = $fund.find('.login_for_payments');
		$notLoggedDiv.hide();
		$logInDiv.fadeIn(300);
	},
	reloadPaymentMethods:function(noLoadingIcon){
		var noLoadingIcon = noLoadingIcon || false;
		var $payment_method_td = $('.payment_method_td');
		if($payment_method_td.length == 1){
			var tdID = $payment_method_td.attr('id');
			var fundID = tdID.substring(18,tdID.length);
			if(!noLoadingIcon){
				$payment_method_td.html(Fundr.getLoadingIcon());
			}
			Ajax.run("paymentView.renderPaymentAccounts",
				function(data){
					$payment_method_td.html(data)
				},
				{fundID:fundID}
			);
		}
	},
	addPaymentMethod:function(radioName){
		var value = Radio.get(radioName);
		if(value == 'add'){
			$('input[name='+radioName+']:checked').prop('checked',false);
			Modal.open('payment_method_form');
		}
	},
	computeCardName:function(){
		var number = $('#pp_full_res').find('input[name=number]').val() || "";
		var type = "CARD";
		var name = $('#pp_full_res').find('input[name=card_name]').val() || "";
		if(number.length >= 13 && name == ""){
			if(number.substring(0,1) == '4'){
				type = 'VISA';
			}else if(+number.substring(0,2) >= 51 && +number.substring(0,2) <= 55){
				type = 'MC';
			}else if(number.substring(0,4) == '6011' || number.substring(0,3) == '644' || number.substring(0,2) == '65'){
				type = 'DISC';
			}else if(number.substring(0,2) == '34' || number.substring(0,2) == '37'){
				type = 'AMEX';
			}
			name = type + ' ENDING ' + number.substring(number.length - 4, number.length);
		}
		$('#pp_full_res').find('input[name=card_name]').val(name);
	},
	changePaymentMethodType:function(){
		var type = Radio.getOptionName('payment_method_id').toLowerCase();
		var $ach = $('div.ach_info');
		var $cc = $('div.credit_card_info');
		// 1 == credit card  0 == bank account
		if(type == 'credit card'){
			$ach.hide();
			$cc.show();
		} else {
			$cc.hide();
			$ach.show();
		}
	},
	computeAccountName:function(){
		var type = Radio.get('account_type').toUpperCase();
		var number = $('#pp_full_res').find('input[name=account_number]').val() || "";
		var name = $('#pp_full_res').find('input[name=card_name]').val() || "";
		if(number.length > 4 && name == ""){
			if(type == 'chx'){
				name = 'CHECKING ';
			} else {
				name = 'SAVING ';
			}
			name = name + number.substring(number.length-4,number.length);
			$('#pp_full_res').find('input[name=card_name]').val(name);
		}
	},
	saveCreditCard:function(){ // type is cc or ach
		if(Valid.validate($('#filterSet_payment_method_form'),true,'.ach_info')){
			Ajax.run("paymentService.savePaymentAccount.test",
				function(data){
					Fund.reloadPaymentMethods();
					Modal.close();
					//TODO: add handle auth.NET responses
				},
				Fund.getPaymentAccountForm('cc')
			);
		}
	},
	saveBankAccount:function(){
		if(Valid.validate($('#filterSet_payment_method_form'),true,'.credit_card_info')){
			Ajax.run("paymentService.savePaymentAccount.test",
				function(data){
					Fund.reloadPaymentMethods();
					Modal.close();
					//TODO: add handle auth.NET responses
				},
				Fund.getPaymentAccountForm('ach')
			);
		}
	},
	getPaymentAccountForm:function(type){
		var $modal = $('div#pp_full_res');
		var data = Fundr.getAjaxData($modal);
		if(type == 'cc'){
			var exclude = Fundr.getAjaxData($modal.find('.ach_info'));
		} else {
			var exclude = Fundr.getAjaxData($modal.find('.credit_card_info'));
		}
		for(var key in exclude){
			delete data[key];
		}
		return data;
	},
	savePaymentPlan:function(fundID){
		var $paymentArea = $('#fund_'+fundID).find('.fund-paymentArea');
		if(true){ // add validation
			Ajax.run("paymentService.savePaymentPlan.test",
				function(data){
					Fund.refresh(fundID);
				},
				Fundr.getAjaxData($paymentArea)
			);
		}
	},
	deletePaymentPlan:function(planID,button){
		var text = $(button).attr('bubble');
		if(confirm(text+'?')){
			Ajax.run("paymentService.deletePaymentPlan.test",
				function(data){
					Fund.refresh(data);
				},
				{paymentPlanID:planID}
			);
		}
	},
	refresh:function(fundID){
		var $fund = $('#fund_'+fundID);
		var $loadingIcon = $('#fund_'+fundID).find('.fund-contents-loading');
		$loadingIcon.fadeIn(300);
		Ajax.run("fundView.renderFunds",
			function(data){
				$fund.fadeOut(function(){
					$fund.replaceWith(data);
				});
			},
			{fundID:fundID,isQuery:'false'}
		);
	},
	cancelPayment:function(paymentID){
		if(confirm('Cancel this payment?')){
			Ajax.run("paymentService.cancelPayment.test",
				function(data){
					Fund.refresh(data);
				},
				{paymentID:paymentID}
			);
		}
	}
};
var Upload = {
	fundID:'XXXXX',
	fileSelected:function(input){
		var $input = $(input),
		inputArray = $input.val().split('.'),
		fileNameArray = $input.val().split('\\'),
		acceptableSuffixes = ".jpg.jpeg.png.gif.",
		message = [],
		$modal = $('#pp_full_res'),
		$upload = $modal.find('#uploadButton');

		Valid.removeMessages($modal);
		
		if(inputArray.length < 2){
			message.push('filename is invalid.');
		} else {
			if(acceptableSuffixes.indexOf('.'+inputArray[inputArray.length-1].toLowerCase()+'.') == -1){
				message.push('.'+inputArray[inputArray.length-1] + ' filetype is not ok');
			}
		}
		if(message.length > 0){
			Valid.showMessages($modal,message);
			$input.val('');
			$upload.fadeOut();
		} else {
			$modal.find('input[name=key]').val(Upload.fundID+"/full."+inputArray[inputArray.length-1]);
			$upload.fadeIn();
		}
	},
	removeMessage:function(){
		Valid.removeMessages($('#pp_full_res'));
	},
	openModal:function(fundID){
		Upload.fundID = fundID;
		Modal.open('upload_form');
	},
	key:'XXXXX',
	init:function(){
		var $iframe = $( "<iframe name='theUploadIframe' src='about:blank' style='display:none;'/>" );
		var $form = Modal.$.find('form:first');
		$form.after($iframe);
		
		$iframe.load(function(){
			var $modal = $('#pp_full_res');
			var file = $modal.find('input[type=file]').val() || "";
			$('#uploadingIcon').remove();
			
			if(file != ""){
				try{
					var result = JSON.parse($(window.frames['theUploadIframe'].document.getElementsByTagName("body")[ 0 ]).html());
					Upload.showTempPhoto(result.key);
					Upload.key = result.key;
				}catch(e){	
					var message = [];
					message.push('Upload Failed');
					message.push('Check filesize is under 2mb');
					message.push('Check filetype is png jpg gif');
					Valid.showMessages($modal,message);
					$modal.find('input[type=file]').val('');
					console.log(e);
				}
			}
		});
	},
	submit:function(){
		var $modal = $('#pp_full_res');
		var $form = $modal.find('form:first');
		var $button = $modal.find('#uploadButton');
		
		$modal.find('input[type=file]').after(Fundr.getLoadingIcon('margin-left:61px;display:none;','uploadingIcon'));
		
		$button.fadeOut('fast',function(){
			$('#uploadingIcon').fadeIn();
		});
		$form.submit();
	},
	showTempPhoto:function(key){
		var $temp = Modal.$.find('#temp-photo');
		var $thumb = Modal.$.find('#thumbnail-photo');
		var $form = Modal.$.find('form:first');
				
		Ajax.run("fileView.renderPhoto",
			function(data){
				$form.hide();
				$temp.replaceWith(data);
				var thumb = "";
				thumb = data.replace('id="temp-photo"','id="thumbnail-photo"');
				thumb = thumb.replace("onload","nothing");
				$thumb.replaceWith(thumb);
			},
			{key:key,onload:'Upload.showTempPhoto2();'}
		);
	},
	width:0,
	height:0,
	showTempPhoto2:function(){
		var $table = Modal.$.find('#temp-photo-table');
		var $image = Modal.$.find('#temp-photo');
		
		Upload.width = $image.width();
		Upload.height = $image.height();
		
		Modal.reposition();
		$image.Jcrop({
			onChange: Upload.showPreview,
			onSelect: Upload.showPreview,
			aspectRatio: 1.578
		},function(){
			Upload.$jCrop = this;
		});
		Upload.$jCrop.setSelect([15,15,165,110]);
		$table.fadeIn('fast');
	},
	showPreview:function(coords){
		var rx = 150 / coords.w;
		var ry = 95 / coords.h;
		
		//var rx = Upload.width / coords.w;
		//var ry = Upload.height / coords.h;

		Modal.$.find('#thumbnail-photo').css({
			width: Math.round(rx * Upload.width) + 'px',
			height: Math.round(ry * Upload.height) + 'px',
			marginLeft: '-' + Math.round(rx * coords.x) + 'px',
			marginTop: '-' + Math.round(ry * coords.y) + 'px'
		});
	},
	saveThumbnail:function(){
		var $button = Modal.$.find('#setThumbnailButton');
		$button.after(Fundr.getLoadingIcon('display:none;','settingThumbnailIcon'));

		$button.fadeOut(function(){
			Modal.$.find('#settingThumbnailIcon').fadeIn();
		});
		
		var coords = Upload.$jCrop.tellSelect();
		var suffix = Upload.key.split('.');
		suffix = suffix[suffix.length-1];

		Ajax.run("fileService.uploadThumbnail",
			function(data){
				setTimeout(function(){
					Modal.close();
					Fund.refresh(Upload.fundID);
				},800);
			},
			{x:coords.x,y:coords.y,h:coords.h,w:coords.w,suffix:suffix,fundID:Upload.fundID}		
		);
	},
	removeThumbnail:function(fundID){
		if(confirm('Remove this image?')){
			Ajax.run("fileService.removeThumbnail",
				function(data){
					setTimeout(function(){
						Fund.refresh(fundID);
					},800);
				},
				{fundID:fundID}
			);
		}
	}
};

Social = {
	facebookShare:function(name,caption,description,link,picture){
		FB.ui(
		  {
		   method: 'feed',
		   name: name,
		   caption: caption,
		   description: description,
		   link: link,
		   picture: picture
		  },
		  function(response) {
		    if (response && response.post_id) {
		      alert('Post was published.');
		    } else {
		      alert('Post was not published.');
		    }
		  }
		);
	}
};

SearchSummary = {
	clearTags:function(that){
		var $tagbox = $('.tag-box');
		$tagbox.find('span.tag-remove').each(function(){
			Tag.remove($(this).find('a'));
		});
		Fund.throttle(Fund.query,'fundsearch',500);
		$(that).animate({opacity:"0"},600);
	},
	clearOwnerName:function(that){
		$('#filterSet_Search').find('[name=owner_name]').val('');
		Fund.throttle(Fund.query,'fundsearch',500);
		$(that).animate({opacity:"0"},600);
	},
	clearStartDate:function(that){
		$('#filterSet_Search').find('[name=start_date]').val('');
		$('#filterSet_Search').find('[name=end_date]').val('');
		Fund.throttle(Fund.query,'fundsearch',500);
		$(that).animate({opacity:"0"},600);
	},
	clearFundID:function(that){
		$('#filterSet_Search').find('[name=fundID]').val('');
		Fund.throttle(Fund.query,'fundsearch',500);
		$(that).animate({opacity:"0"},600);
	},
	clearCity:function(that){
		$('#filterSet_Search').find('[name=City]').val('');
		Fund.throttle(Fund.query,'fundsearch',500);
		$(that).animate({opacity:"0"},600);
	},
	clearState:function(that){
		$('#filterSet_Search').find('[name=state_ID]').val('');
		Fund.throttle(Fund.query,'fundsearch',500);
		$(that).animate({opacity:"0"},600);
	},
	clearTitleDescription:function(that){
		$('#filterSet_Search').find('[name=title_description]').val('');
		Fund.throttle(Fund.query,'fundsearch',500);
		$(that).animate({opacity:"0"},600);
	},
	clearZip:function(that){
		$('#filterSet_Search').find('[name=Zip]').val('');
		Fund.throttle(Fund.query,'fundsearch',500);
		$(that).animate({opacity:"0"},600);
	},
	clearAll:function(){
		$('.search-summary').find('a').animate({opacity:"0"},600);
		SearchSummary.clearZip();
		SearchSummary.clearTitleDescription();
		SearchSummary.clearCity();
		SearchSummary.clearFundID();
		SearchSummary.clearStartDate();
		SearchSummary.clearOwnerName();
		SearchSummary.clearTags();
		SearchSummary.clearState();
	}
};

